//
//  BGLeadPageVC.m
//  test
//
//  Created by 周博 on 15/11/21.
//  Copyright © 2015年 周博. All rights reserved.
//

#import "BGLeadPageVC.h"
#import "BGControl.h"

#define kTime 2.f
@interface BGLeadPageVC ()<UIScrollViewDelegate>
{
    NSInteger timeCount;
    
    NSInteger _hiddenValue;
}
@property (nonatomic,strong) UIView *launchScreen;

@property (nonatomic,strong) UIScrollView *mainScrollView;
@property (nonatomic,strong) NSArray *picArray;
@property (nonatomic,strong) NSURLSessionTask *downloadTask;
@property (nonatomic,strong) UIPageControl *pageControl;

@property (nonatomic,strong) MBProgressHUD *hub;
@end

@implementation BGLeadPageVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

//    [self changeColor];
    
//    NSString *isFirst = [[NSUserDefaults standardUserDefaults] valueForKey:@"FIRST"];
//    if ([isFirst integerValue] < 1) {
        [self hiddenView];
//    }else{
////        [self creatLaunchScreen];
//        [self hiddenView];
//    }
    
}



- (void)viewWillAppear:(BOOL)animated{
}

/**
 *  创建启动页
 */
- (void)creatLaunchScreen{
    
    NSString *imageName = @"loading页2.png";
    
    self.launchScreen = [BGControl creatViewWithFrame:CGRectMake(0, 0, kScreenSize.width, kScreenSize.height) backgroundColor:[UIColor whiteColor] isLayer:NO cornerRadius:0];
    UIImageView * imageView = [BGControl creatImageViewWithFrame:CGRectMake(0, 0, kScreenSize.width, kScreenSize.height) image:imageName isWebImage:NO holdOnImage:nil isLayer:NO cornerRadius:0];
    [self.launchScreen addSubview:imageView];
    [self.view addSubview:self.launchScreen];
    
    [NSTimer scheduledTimerWithTimeInterval:kTime target:self selector:@selector(countTimes) userInfo:nil repeats:NO];
}

/**
 *  计时器的选择事件
 */
- (void)countTimes{
    [UIView animateWithDuration:1.0f animations:^{
        self.launchScreen.alpha = 1;
    }];
    [self hiddenView];
}

- (void)hiddenView{
//    [self isFirstLogin:_hiddenValue];
//    [[AFClient shareInstance] hiddenViewProgressBlock:^(NSProgress *progress) {
//        
//    } success:^(id responseBody) {
//        if ([responseBody[@"code"] integerValue]== 200) {
//            _hiddenValue = [responseBody[@"data"] integerValue];
//            [self isFirstLogin:_hiddenValue];
//        }
//    } failure:^(NSError *error) {
//        
//    }];
    _hiddenValue = 1;
    [self isFirstLogin:_hiddenValue];

}

/**
 *  创建滚动视图  -> 引导页
 */
- (void)creatMainScrollView{
    self.picArray = [NSArray array];
    self.picArray = @[@"引导页01.jpg",@"引导页02.jpg",@"引导页03.jpg"];
    
    self.mainScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, kScreenSize.width, kScreenSize.height)];
    self.mainScrollView.contentSize = CGSizeMake(kScreenSize.width * self.picArray.count, kScreenSize.height);
    //设置 分成不同页面
    self.mainScrollView.pagingEnabled = YES;
    //代理
    self.mainScrollView.delegate = self;
    //设置是否可以左右滑动
    self.mainScrollView.showsHorizontalScrollIndicator = NO;
    self.mainScrollView.showsVerticalScrollIndicator = NO;
    //设置反弹动画
    self.mainScrollView.bounces = NO;
    //背景颜色
    self.mainScrollView.backgroundColor = [UIColor whiteColor];
    //是否 可翻页
    self.mainScrollView.delaysContentTouches = YES;
    //触摸事件
    self.mainScrollView.canCancelContentTouches = NO;
    //用户交互
    self.mainScrollView.userInteractionEnabled = YES;
    
    //循环将粘有button的imageView 粘贴到scrollView上
    for (NSInteger i = 0; i < self.picArray.count; i++) {
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(i * kScreenSize.width, 0, kScreenSize.width, kScreenSize.height)];
        
        imageView.image = [UIImage imageNamed:self.picArray[i]];
        
        if (self.picArray.count - 1 == i) {
            
            UIView *inView2 = [[UIView alloc] initWithFrame:CGRectMake((kScreenSize.width - (kScreenSize.width/2))/2, kScreenSize.height - 150, kScreenSize.width/2, 40)];
            inView2.layer.masksToBounds = YES;
            inView2.layer.cornerRadius = 10;
            inView2.layer.borderColor = [[UIColor groupTableViewBackgroundColor] CGColor];
            inView2.layer.borderWidth = 1.f;
            inView2.backgroundColor = [kWhiteColor colorWithAlphaComponent:0.5];
            
            UILabel *contentLabel2 = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, inView2.sizeWidth, inView2.sizeHeight)];
            contentLabel2.font = [UIFont systemFontOfSize:20];
            contentLabel2.text = @"立即登录";
            contentLabel2.textAlignment = NSTextAlignmentCenter;
            contentLabel2.textColor = kColorFrom0x(0xd53c3e);
            
            [inView2 addSubview:contentLabel2];
            [imageView addSubview:inView2];
            
            UIButton *button2 = [UIButton buttonWithType:UIButtonTypeSystem];
            button2.frame = contentLabel2.frame;
            [button2 addTarget:self action:@selector(scrollViewButtonClick2:) forControlEvents:UIControlEventTouchUpInside];
            [inView2 addSubview:button2];
            imageView.userInteractionEnabled = YES;
        }
        [self.mainScrollView addSubview:imageView];
    }
    //创建UIPageControl
    _pageControl = [[UIPageControl alloc] initWithFrame:CGRectMake(0, kScreenSize.height - 80, kScreenSize.width, 30)];  //创建UIPageControl，位置在屏幕最下方。
    _pageControl.userInteractionEnabled = YES;

    _pageControl.numberOfPages = _picArray.count;//总的图片页数
    _pageControl.currentPage = 0; //当前页
    [_pageControl addTarget:self action:@selector(pageTurn:) forControlEvents:UIControlEventValueChanged];  //用户点击UIPageControl的响应函数
    [self.view addSubview:self.mainScrollView];
    [self.view addSubview:_pageControl];  //将UIPageControl添加到主界面上。
    
}


- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

//其次是UIScrollViewDelegate的scrollViewDidEndDecelerating函数，用户滑动页面停下后调用该函数。

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    //更新UIPageControl的当前页
    CGPoint offset = scrollView.contentOffset;
    CGRect bounds = scrollView.frame;
    [_pageControl setCurrentPage:offset.x / bounds.size.width];
    NSLog(@"%f",offset.x / bounds.size.width);
}

//然后是点击UIPageControl时的响应函数pageTurn
- (void)pageTurn:(UIPageControl*)sender
{
    //令UIScrollView做出相应的滑动显示
    CGSize viewSize = _mainScrollView.frame.size;
    CGRect rect = CGRectMake(sender.currentPage * viewSize.width, 0, viewSize.width, viewSize.height);
    [_mainScrollView scrollRectToVisible:rect animated:YES];
}

/**
 *  是否是第一次登录
 */
- (void)isFirstLogin:(NSInteger)isHidden{
    NSString * isFirst = [[NSUserDefaults standardUserDefaults] valueForKey:@"FIRST"];
//    if (isFirst.integerValue < 1) {
////        [self creatMainScrollView];
//    }else{
        [self autoLogin];
//    }
}

- (void)scrollViewButtonClick2:(UIButton *)button{
    [[NSUserDefaults standardUserDefaults] setValue:@"1" forKey:@"FIRST"];
    [self autoLogin];
}


#pragma mark 自动登录
/**
 *  自动登录
 *
 *  @param mobile 如果登录过,会从本地获取文件取出 mobile 的值,完成自动登录
 */
- (void)autoLogin{
    if ([kUserId integerValue] > 0) {
        [self autoLoginFun];
    }else{
        [[NSNotificationCenter defaultCenter] postNotificationName:@"sign" object:nil];
    }
}

- (void)autoLoginFun{
    [self.hub hideAnimated:YES];
    
    self.hub = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    // Set the label text.
    self.hub.label.text = NSLocalizedString(@"登录中...", @"HUD loading title");
    [[AFClient shareInstance] checkMobile:kMobile progressBlock:nil success:^(id responseBody) {
        [self.hub hideAnimated:YES];
        [self getPowerVerson];
//        NSData * data;
//        NSString *result = [[NSString alloc] initWithData:responseBody  encoding:NSUTF8StringEncoding];
//        NSLog(@"%@",result);
        if ([responseBody[@"code"] integerValue] == 200) {
            [[NSNotificationCenter defaultCenter] postNotificationName:@"login" object:nil];
        }else{
            [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"mobile"];
            [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"userName"];
            [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"userId"];
            [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"created"];
            [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"adminUserId"];
            [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"created"];
            [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"cityName"];
            [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"organization_id"];
            [[NSUserDefaults standardUserDefaults]removeObjectForKey:@"admin"];

            [[NSNotificationCenter defaultCenter] postNotificationName:@"sign" object:nil];
        }
    } failure:^(NSError *error) {
        [self.hub hideAnimated:YES];
    }];
}

- (void)getPowerVerson{
    [[AFClient shareInstance] getNewVersonAboutPowerProgressBlock:nil success:^(id responseBody) {
        if ([responseBody[@"code"] integerValue] == 200) {
            NSString *verson = responseBody[@"data"];
            if (![BGFunctionHelper isNULLOfString:verson]) {
                [[NSUserDefaults standardUserDefaults] setValue:verson forKey:@"powerVerson"];
            }
        }
    } failure:^(NSError *error) {
        
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
//    [GetUserInfo removeUserInfo];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"sign" object:nil];
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
